<?php

namespace backend\components\widget\file;

use backend\assets\SortableAsset;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\JsExpression;
use yii\widgets\InputWidget;

/**
 * UploadWidget
 * @property-read \yii\web\JsExpression $uploadSuccess
 * @property-read \yii\web\JsExpression $afterSelected
 * @package backend\components\widget\file
 */
class UploadWidget extends InputWidget
{

    /**
     * @var array
     */
    public $uploadOptions = [];

    /**
     * @var string
     */
    public $type = 'image';

    /**
     * init
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        parent::init();

        $this->value = $this->hasModel() ? Html::getAttributeValue($this->model, $this->attribute) : $this->value;

        $this->name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->name;

        $this->uploadOptions = array_merge([
            'name'           => $this->name,
            'type'           => $this->type,
            'uploadUrl'      => Url::to('/file/upload'),
            'uploadCheckUrl' => Url::to('/file/check'),
            'uploadPath'     => $this->type,
            'uploadEle'      => $this->getId(),
            'multiple'       => 1,
            'defaultImage'   => '/images/image.png',
        ], params('upload')[$this->type] ?? [], $this->uploadOptions);

        $this->registerJsCode();
    }

    /**
     * run
     * @return string
     */
    public function run()
    {

        if($this->uploadOptions['multiple'] > 1){

            SortableAsset::register($this->view);

            return $this->render('multiple', [
                'name'          => $this->name,
                'imageList'     => $this->value,
                'type'          => $this->type,
                'options'       => $this->options,
                'uploadOptions' => $this->uploadOptions,
            ]);
        }else{
            return $this->render('upload', [
                'name'          => $this->name,
                'value'         => $this->value,
                'type'          => $this->type,
                'options'       => $this->options,
                'uploadOptions' => $this->uploadOptions,
            ]);
        }
    }

    /**
     * registerJsCode
     */
    public function registerJsCode()
    {
        $uploadOptions = $this->uploadOptions;

        $uploadOptions['uploadEle'] = '#' . $uploadOptions['uploadEle'];

        $uploadOptions['mimeTypes'] = !empty($this->uploadOptions['mimeTypes'])?explode(',', $this->uploadOptions['mimeTypes']):[];

        $uploadOptions['maxSize'] = $this->uploadOptions['maxSize'] ?? 0;

        $uploadOptions = Json::htmlEncode($uploadOptions);

        UploadAsset::register($this->view);

        $js = <<<JS
(new Upload()).init({$uploadOptions}).click();
JS;

        $this->view->registerJs($js, $this->view::POS_READY);
    }

}